//
//  SNStepChartVc.m
//  project
//
//  Created by 黄建华 on 2017/11/29.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNStepChartVc.h"

@interface SNStepChartVc ()

@property (nonatomic, strong) SNStepChartView *ChartView;
@property (nonatomic, strong) NSMutableArray  *modelArray;
@property (nonatomic, assign) SelectDateType  lastType;

@end

@implementation SNStepChartVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _ChartView                 = [[SNStepChartView alloc] initWithFrame:SNFRAME(0, 70 +FitSimpleIpx(0, 20), HHHWIDTH, HHHHEIGHT *0.4 -FitSimpleIpx(0, 20))];
    _ChartView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_ChartView];
    
    NSArray *array1 = [NSArray arrayWithObjects:SN_Text(@"达标天数"), SN_Text(@"日均步数"), SN_Text(@"日均消耗大卡"), SN_Text(@"总距离长度"), SN_Text(@"日均距离"), SN_Text(@"总步数"), nil];
    
    CGFloat height      = FitSimpleSize(75, 80, 100, 120, 130);
    CGFloat labelHeight = FitSimpleSize(0, 0, 10, 20, 27);
    UIView  *line0      = [[UIView alloc] init];
    line0.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43, HHHWIDTH, 5.0);
    line0.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line0];
    
    UIView *line1 = [[UIView alloc] init];
    line1.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43 + height, HHHWIDTH, 1);
    line1.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc] init];
    line2.frame           = SNFRAME(0, _ChartView.origin.y + HHHHEIGHT *0.43 + height*2, HHHWIDTH, 5.0);
    line2.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line2];
    
    UIView *line3 = [[UIView alloc] init];
    line3.frame           = SNFRAME(HHHWIDTH /3, _ChartView.origin.y + HHHHEIGHT *0.43, 1, height*2);
    line3.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line3];
    
    UIView *line4 = [[UIView alloc] init];
    line4.frame           = SNFRAME(HHHWIDTH /3 *2, _ChartView.origin.y + HHHHEIGHT *0.43, 1, height*2);
    line4.backgroundColor = SNCOLORGRAYLINE;
    [self.view addSubview:line4];
    
    for (int i = 0; i < 6; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.text          = array1[i];
        unitLabel.textColor     = SNCOLORGRAY;
        unitLabel.font          = SNSFONT(14.0);
        unitLabel.adjustsFontSizeToFitWidth = YES;
        if (i < 3) {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40, HHHWIDTH /3, 20);
        } else {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i - HHHWIDTH, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 + height, HHHWIDTH /3, 20);
        }
        [self.view addSubview:unitLabel];
    }
    // 数值显示Label
    for (int i = 0; i < 6; i++) {
        UILabel *unitLabel = [[UILabel alloc] init];
        unitLabel.textAlignment = NSTextAlignmentCenter;
        unitLabel.textColor     = SNCOLORBLACK;
        unitLabel.font          = SNFONT(13.0);
        unitLabel.tag           = 100 + i;
        if (i < 3) {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 - 22, HHHWIDTH /3, 20);
        } else {
            unitLabel.frame = SNFRAME(HHHWIDTH /3 *i - HHHWIDTH, labelHeight +_ChartView.origin.y + HHHHEIGHT *0.43 + 40 + height - 22, HHHWIDTH /3, 20);
        }
        [self.view addSubview:unitLabel];
    }
    
    [self selectType:SelectDateWeek];
}

- (void)selectType:(SelectDateType)type {
    //    NSLog(@"周月年选择了>>>>>>%d",type);
    _lastType = type;
    SportModel     *model = [SportModel getSportModelFromDBWith:SN_PublicClass.selectDate];
    NSMutableArray *array = [NSMutableArray array];
    if (type == SelectDateDay) {
        array = [NSMutableArray arrayWithArray:model.stepArray];
    }
    
    if (type == SelectDateWeek) {
        KK_ShareData.weekStepFinishArray = [NSMutableArray array];
        for (int i = 0; i < 7; i++) {
            NSDate   *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:1];
            NSDate   *Date        = [first dateAfterDay:i];
            NSString *firstString = [Date dateToDayString];
            NSString *sss         = [NSString stringWithFormat:@"SELECT step FROM SportModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
            NSString *stepValue   = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
            [array addObject:stepValue ? stepValue : @"0"];
            
            
            NSString *sFinish   = [NSString stringWithFormat:@"SELECT stepTarget FROM SportModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
            NSString *stepFinsh = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sFinish arguments:nil];
            [KK_ShareData.weekStepFinishArray addObject:stepFinsh ? stepFinsh : @"0"];
        }
    }
    
    if (type == SelectDateMonth) {
        KK_ShareData.monthStepFinishArray = [NSMutableArray array];
        NSInteger monthCount = SN_PublicClass.selectDate.daysInMonth;
        for (int i = 0; i < monthCount; i++) {
            NSDate   *first       = [SN_PublicClass getMonthBeginAndEndWith:SN_PublicClass.selectDate withType:2];
            NSDate   *Date        = [first dateAfterDay:i];
            NSString *firstString = [Date dateToDayString];
            NSString *sss         = [NSString stringWithFormat:@"SELECT step FROM SportModel WHERE dateString ='%@' and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
            NSString *stepValue   = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sss arguments:nil];
            [array addObject:stepValue ? stepValue : @"0"];
            
            NSString *sFinish   = [NSString stringWithFormat:@"SELECT stepTarget FROM SportModel WHERE dateString ='%@'and dateString <='%@' and user_id = '%@'", firstString, [[NSDate date]dateToDayString], SN_USER.user_id];
            NSString *stepFinsh = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:sFinish arguments:nil];
            [KK_ShareData.monthStepFinishArray addObject:stepFinsh ? stepFinsh : @"0"];
        }
//                  NSLog(@"KK_ShareData.monthStepFinishArray>>>>%@",KK_ShareData.monthStepFinishArray);
    }
    
    if (type == SelectDateYear) {
        for (int i = 1; i <= 12; i++) {
            NSString *monthStep  = [NSString stringWithFormat:@"SELECT SUM(step) AS OrderTotal FROM SportModel WHERE yearCount =%d and monthCount = %d  and dateString <='%@' and user_id = '%@' ", model.yearCount, i, [[NSDate date]dateToDayString], SN_USER.user_id];
            NSString *monthSteps = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:monthStep arguments:nil];
            [array addObject:StrByInt(monthSteps.intValue)];
        }
    }
    
    [_ChartView UpdateViewWithType:type withArray:array];
    [self updateValueLabel:type];
}

- (void)updateValueLabel:(SelectDateType)type {
    //数据加载
    NSMutableArray *array2 = [NSMutableArray array];
    // 周达标天数
    
    NSArray *time = [SN_PublicClass getBeginDateStringAndEndWith:SN_PublicClass.selectDate withType:type];
    
    NSString *finish  = [NSString stringWithFormat:@"SELECT SUM(stepFinish) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@' and stepquality = 1 and step >0", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *finishs = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:finish arguments:nil];

    [array2 addObject:StrByInt(finishs.intValue)];
    
    NSString *aveStep  = [NSString stringWithFormat:@"SELECT AVG(step) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and step>0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *aveSteps = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:aveStep arguments:nil];
    [array2 addObject:StrByInt(aveSteps.intValue)];
    
    NSString *avecalory  = [NSString stringWithFormat:@"SELECT AVG(calory) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and step>0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *avecalorys = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:avecalory arguments:nil];
    [array2 addObject:StrByInt(avecalorys.intValue)];
    
    NSString *distance  = [NSString stringWithFormat:@"SELECT SUM(distance) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *distances = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:distance arguments:nil];
    NSString *tDStr     = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.2f %@", roundf(distances.floatValue*0.0006214*100)/100, SN_Text(@"英里")] : [NSString stringWithFormat:@"%.2f %@", distances.floatValue/1000, SN_Text(@"千米")];
    [array2 addObject:tDStr];
    
    NSString *avedistance  = [NSString stringWithFormat:@"SELECT AVG(distance) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and step>0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *avedistances = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:avedistance arguments:nil];
    NSString *aDStr        = SN_USER.isMetricSystem ? [NSString stringWithFormat:@"%.2f %@", roundf(avedistances.floatValue*0.0006214*100)/100, SN_Text(@"英里")] : [NSString stringWithFormat:@"%.2f %@", avedistances.floatValue/1000, SN_Text(@"千米")];
    [array2 addObject:aDStr];
    
    NSString *totalStep  = [NSString stringWithFormat:@"SELECT SUM(step) AS OrderTotal FROM SportModel WHERE dateString >='%@' and dateString <='%@' and step>0 and user_id = '%@'", [time firstObject], [time lastObject], SN_USER.user_id];
    NSString *totalStepS = [[SportModel getUsingLKDBHelper]executeScalarWithSQL:totalStep arguments:nil];
    
    [array2 addObject:[NSString stringWithFormat:@"%ld %@", totalStepS.integerValue, SN_Text(@"步")]];
    
    if (array2.count > 0) {
        for (UILabel *label in self.view.subviews) {
            if ([label isKindOfClass:[UILabel class]]) {
                if (label.tag >= 100) {
                    label.text = array2[label.tag - 100];
                }
            }
        }
    }
}

- (void)updateView:(KKBLEAcceptType)type {
    if (type == KKBLEAcceptTypeRealtimeSport || type == KKBLEAcceptTypeDataSport) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateView) object:nil];
        [self performSelector:@selector(delayUpdateView) withObject:nil afterDelay:3.0];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateView) object:nil];
}

- (void)delayUpdateView {
    [self selectType:_lastType];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

